package com.example.yichuangyun.ui.activity.index;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ActivityStatisticsDailyBinding;
import com.example.yichuangyun.dialog.TimePicker;
import com.example.yichuangyun.http.HttpRespond;
import com.example.yichuangyun.http.MyObserver;
import com.example.yichuangyun.http.RetrofitHelper;
import com.example.yichuangyun.model.business.LabelModel;
import com.example.yichuangyun.model.index.StatisticsDataModel;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.base.BaseViewModel;
import com.example.yichuangyun.ui.adapter.EmptyRecyclerCommonAdapter;
import com.example.yichuangyun.ui.adapter.RecyclerCommonAdapter;
import com.example.yichuangyun.ui.adapter.RecyclerViewHolder;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.DateUtil;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 统计日报
 */
public class StatisticsDailyActivity extends BaseActivity<ActivityStatisticsDailyBinding, BaseViewModel> {

    private String chooseType = "";
    private String chooseDateStart = "";
    private String chooseDateEnd = "";
    private int page = 1;
    private EmptyRecyclerCommonAdapter<StatisticsDataModel.StatisticsModel> adapter;
    private List<StatisticsDataModel.StatisticsModel> data = new ArrayList<>();
    private final List<LabelModel> timeData = new ArrayList<>();
    private TimePicker timePicker;
    private boolean isStartTime;
    private RecyclerCommonAdapter<LabelModel> timeAdapter;
    /**
     * 0统计日报、1佣金统计、2业绩统计
     */
    private int flag;

    private String userId;

    @Override
    protected BaseViewModel bindModel() {
        return getViewModel(this, BaseViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void initData() {
        requestTranslucentStatusBar(false);
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            flag = bundle.getInt(Constant.flagKey);
            switch (flag) {
                case 0:
                    binding.tvMainTitle.setText(getString(R.string.statistics_daily));
                    chooseDateStart = DateUtil.getCurrentDay();
                    chooseDateEnd = DateUtil.getCurrentDay();
                    binding.tvTime.setText(chooseDateStart);
                    break;
                case 1:
                    binding.tvMainTitle.setText(getString(R.string.commission_statistics));
                    binding.tvTitle1.setText(getString(R.string.service_no_name));
                    binding.tvTitle3.setText(getString(R.string.sign_time));
                    binding.tvTitle4.setText(getString(R.string.current_money));
                    chooseDateStart = DateUtil.getFirstDayOfMonth(DateUtil.LONG_DATE_FORMAT);
                    chooseDateEnd = DateUtil.getLastDayOfMonth(DateUtil.LONG_DATE_FORMAT);
                    binding.tvTime.setText(getString(R.string.time_scope, chooseDateStart, chooseDateEnd));
                    break;
                case 2:
                    binding.tvMainTitle.setText(getString(R.string.performance_statistics));
                    binding.tvTitle1.setText(getString(R.string.service_no_name));
                    binding.tvTitle3.setText(getString(R.string.sign_time));
                    binding.tvTitle4.setText(getString(R.string.into_account));
                    chooseDateStart = DateUtil.getFirstDayOfMonth(DateUtil.LONG_DATE_FORMAT);
                    chooseDateEnd = DateUtil.getLastDayOfMonth(DateUtil.LONG_DATE_FORMAT);
                    binding.tvTime.setText(getString(R.string.time_scope, chooseDateStart, chooseDateEnd));
                    userId = bundle.getString(Constant.userIdKey);
                    break;
            }
        }
        binding.tvUpdateTime.setText(getString(R.string.last_update_time, DateUtil.getNowTime()));
        GridLayoutManager layoutManager = new GridLayoutManager(this, 3, LinearLayoutManager.VERTICAL, false);
        binding.includeSelect.recyclerViewTime.setLayoutManager(layoutManager);

        timeData.add(new LabelModel(getString(R.string.this_month), false));
        timeData.add(new LabelModel(getString(R.string.last_month), false));
        timeData.add(new LabelModel(getString(R.string.this_week), false));
        timeData.add(new LabelModel(getString(R.string.last_week), false));
        timeData.add(new LabelModel(getString(R.string.yesterday), false));
        timeData.add(new LabelModel(getString(R.string.today), false));
        getStatistics(page);
        initTimePicker();
    }

    private void initTimePicker() {
        timePicker = new TimePicker(this) {
            @Override
            public void confirm(String date) {
                if (isStartTime) {
                    binding.includeSelect.tvStartTime.setText(date);
                } else {
                    binding.includeSelect.tvEndTime.setText(date);
                }
                for (LabelModel labelModel : timeData) {
                    labelModel.setSelect(false);
                }
                timeAdapter.notifyDataSetChanged();
                chooseType = "";
            }
        };
    }

    private void getStatistics(int page) {
        JSONObject requestDate = new JSONObject();
        try {
            requestDate.put("userId", userId);
            if (flag == 1) { // 佣金
//                requestDate.put("page", page);
//                requestDate.put("pageSize", Constant.pageSize20);
//                requestDate.put("starCreateTime", chooseDateStart + " 00:00:00");
//                requestDate.put("endCreateTime", chooseDateEnd + " 23:59:59");
                requestDate.put("page", page);
                requestDate.put("pageSize", Constant.pageSize20);
                requestDate.put("isMy", 1);
                requestDate.put("roadCommission", 0);
                requestDate.put("starSignTime", chooseDateStart + " 00:00:00");
                requestDate.put("endSignTime", chooseDateEnd + " 23:59:59");
            } else {
                requestDate.put("current", page);
                requestDate.put("size", Constant.pageSize20);
                requestDate.put("dateTimeStart", chooseDateStart);
                requestDate.put("dateTimeEnd", chooseDateEnd);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestDate.toString());
        Observable<HttpRespond<StatisticsDataModel>> statistics = null;
        if (flag == 0) {
            statistics = RetrofitHelper.getService().getStatistics(requestBody);
        } else if (flag == 1) {
            statistics = RetrofitHelper.getService().getCommissionStatistics(requestBody);
        } else {
            statistics = RetrofitHelper.getService().getMonthPerformanceReportDetail(requestBody);
        }
        RetrofitHelper.getInstance().execute(statistics, new MyObserver<HttpRespond<StatisticsDataModel>>() {
            @Override
            protected void onSuccess(HttpRespond<StatisticsDataModel> statisticsDataModelHttpRespond) {
                if (statisticsDataModelHttpRespond.code == Constant.SUCCESS) {
                    if (null != statisticsDataModelHttpRespond.data.getRecords()) {
                        binding.tvUpdateTime.setText(getString(R.string.last_update_time, DateUtil.getNowTime()));
                        List<StatisticsDataModel.StatisticsModel> list = statisticsDataModelHttpRespond.data.getRecords();
                        if (list.size() < Constant.pageSize) {
                            binding.smartRefreshLayout.finishLoadMoreWithNoMoreData();
                        }
                        if (page == 1) {
                            binding.smartRefreshLayout.resetNoMoreData();
                            data = list;
                            adapter.onRefresh(list);
                            binding.smartRefreshLayout.finishRefresh();
                        } else {
                            adapter.addData(list);
                            binding.smartRefreshLayout.finishLoadMore();
                        }
                    }
                }
            }
        });
    }

    @Override
    public void initCtrl() {
        adapter = new EmptyRecyclerCommonAdapter<StatisticsDataModel.StatisticsModel>(context, R.layout.item_statistics, data) {
            @SuppressLint("SetTextI18n")
            @Override
            public void convert(RecyclerViewHolder holder, StatisticsDataModel.StatisticsModel item, int position) {
                TextView tvTex1 = holder.getView(R.id.tv_tex1);
                TextView tvTex2 = holder.getView(R.id.tv_tex2);
                TextView tvTex3 = holder.getView(R.id.tv_tex3);
                switch (flag) {
                    case 0:
                        tvTex1.setText(CommonUtil.checkText(item.getDateTime()));
                        tvTex2.setText(TextUtils.isEmpty(item.getCallNum()) ? "0" : item.getCallNum());
                        tvTex3.setText(TextUtils.isEmpty(item.getCallTime()) ? "00:00:00" : DateUtil.getTimeBySecond2(Integer.parseInt(item.getCallTime())));
                        break;
                    case 1:
                        tvTex1.setText(item.getServiceCode() + "\n" + item.getServiceName());
                        if (!TextUtils.isEmpty(item.getSignTime()) && item.getSignTime().length() > 9) {
                            tvTex2.setText(item.getSignTime().substring(0, 10));
                        } else {
                            tvTex2.setText(CommonUtil.setText3(item.getSignTime()));
                        }
                        tvTex3.setText(!TextUtils.isEmpty(item.getAmount()) ? item.getAmount() : "0.00");
                        break;
                    case 2:
                        tvTex1.setText(item.getCid() + "\n" + item.getServiceName());
                        if (!TextUtils.isEmpty(item.getDate()) && item.getDate().length() > 9) {
                            tvTex2.setText(item.getDate().substring(0, 10));
                        } else {
                            tvTex2.setText(CommonUtil.setText3(item.getDate()));
                        }
                        tvTex3.setText(TextUtils.isEmpty(item.getAmount()) ? "0.00" : item.getAmount());
                        break;
                }
            }
        };
        binding.recyclerView.setAdapter(adapter);

        timeAdapter = new RecyclerCommonAdapter<LabelModel>(context, R.layout.item_time, timeData) {
            @Override
            public void convert(RecyclerViewHolder holder, LabelModel model, int position) {
                TextView tvLabel = holder.getView(R.id.tv_label);
                tvLabel.setTextColor(model.isSelect() ? 0xFF426FFF : 0xFF8D9AA9);
                tvLabel.setBackgroundResource(model.isSelect() ? R.drawable.shape_time_bg_sel : R.drawable.shape_time_bg_def);
                tvLabel.setText(model.getRemark());
            }
        };
        binding.includeSelect.recyclerViewTime.setAdapter(timeAdapter);
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initClick() {
        binding.ivBack.setOnClickListener(v -> finish());
        binding.ivRight.setOnClickListener(v -> binding.drawerLayout.openDrawer(GravityCompat.END));
        binding.smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getStatistics(page);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getStatistics(page);
            }
        });
        timeAdapter.setOnItemClickListener((parent, view, position) -> {
            for (LabelModel labelModel : timeData) {
                labelModel.setSelect(false);
            }
            timeData.get(position).setSelect(true);
            chooseType = timeData.get(position).getRemark();
            timeAdapter.notifyDataSetChanged();
            binding.includeSelect.tvStartTime.setText("");
            binding.includeSelect.tvEndTime.setText("");
        });

        binding.includeSelect.tvConfirm.setOnClickListener(v -> {
            binding.drawerLayout.closeDrawers();
            String mStartTime = binding.includeSelect.tvStartTime.getText().toString();
            String mEndTime = binding.includeSelect.tvEndTime.getText().toString();
            if (!TextUtils.isEmpty(mStartTime)) {
                chooseDateStart = mStartTime;
            }
            if (!TextUtils.isEmpty(mEndTime)) {
                chooseDateEnd = mEndTime;
            }

            switch (chooseType) {
                case "本月":
                    chooseDateStart = DateUtil.getFirstDayOfMonth(DateUtil.LONG_DATE_FORMAT);
                    chooseDateEnd = DateUtil.getLastDayOfMonth(DateUtil.LONG_DATE_FORMAT);
                    break;
                case "上月":
                    chooseDateStart = DateUtil.getFirstDayOfLastMonth(DateUtil.LONG_DATE_FORMAT);
                    chooseDateEnd = DateUtil.getLastDayOfLastMonth(DateUtil.LONG_DATE_FORMAT);
                    break;
                case "上上月":
                    chooseDateStart = DateUtil.getFirstDayOfLastTwoMonth(DateUtil.LONG_DATE_FORMAT);
                    chooseDateEnd = DateUtil.getLastDayOfLastTwoMonth();
                    break;
                case "本周":
                    chooseDateStart = DateUtil.getThisWeekTimeIntervalStart(DateUtil.LONG_DATE_FORMAT);
                    chooseDateEnd = DateUtil.getThisWeekTimeIntervalEnd(DateUtil.LONG_DATE_FORMAT);
                    break;
                case "上周":
                    chooseDateStart = DateUtil.getLastWeekTimeIntervalStart(DateUtil.LONG_DATE_FORMAT);
                    chooseDateEnd = DateUtil.getLastWeekTimeIntervalEnd(DateUtil.LONG_DATE_FORMAT);
                    break;
                case "昨天":
                    chooseDateStart = DateUtil.befoDay();
                    chooseDateEnd = DateUtil.befoDay();
                    break;
                case "今天":
                    chooseDateStart = DateUtil.getCurrentDay();
                    chooseDateEnd = DateUtil.getCurrentDay();
                    break;
            }
            if (!TextUtils.isEmpty(chooseType)) {
                binding.tvTime.setText(chooseType.equals(getString(R.string.yesterday))
                        || chooseType.equals(getString(R.string.today))
                        ? chooseDateStart : getString(R.string.time_scope, chooseDateStart, chooseDateEnd));
            } else {
                if (!TextUtils.isEmpty(chooseDateStart) && !TextUtils.isEmpty(chooseDateEnd)) {
                    binding.tvTime.setText(chooseDateStart.equals(chooseDateEnd) ? chooseDateStart
                            : getString(R.string.time_scope, chooseDateStart, chooseDateEnd));
                }
            }
            page = 1;
            binding.smartRefreshLayout.autoRefresh();
            binding.recyclerView.scrollToPosition(0);
        });

        binding.includeSelect.tvReset.setOnClickListener(v -> {
            for (LabelModel labelModel : timeData) {
                labelModel.setSelect(false);
            }
            timeAdapter.notifyDataSetChanged();
            binding.includeSelect.tvStartTime.setText("");
            binding.includeSelect.tvEndTime.setText("");
            chooseType = "";
            if (flag == 0) {
                chooseDateStart = DateUtil.getCurrentDay();
                chooseDateEnd = DateUtil.getCurrentDay();
                binding.tvTime.setText(chooseDateStart);
            } else {
                chooseDateStart = DateUtil.getFirstDayOfMonth(DateUtil.LONG_DATE_FORMAT);
                chooseDateEnd = DateUtil.getLastDayOfMonth(DateUtil.LONG_DATE_FORMAT);
                binding.tvTime.setText(getString(R.string.time_scope, chooseDateStart, chooseDateEnd));
            }
        });

        binding.includeSelect.tvStartTime.setOnClickListener(v -> {
            isStartTime = true;
            timePicker.showPickerView();
        });
        binding.includeSelect.tvEndTime.setOnClickListener(v -> {
            isStartTime = false;
            timePicker.showPickerView();
        });
    }
}